<?php
class FeedBackService
{
	public function feedBackInfo($data)
	{
		try
		{
			$this->verifyFeedBack($data);
			DB::transaction(function() use($data)
			{
				$feedBack=new Feedback;
				$feedBack->comments=$data['comments'];
				$feedBack->name=$data['name'];
				$feedBack->email=$data['email'];
				$feedBack->ischeck=false;
				$feedBack->save();
				$this->sendMail($data);
			});
			throw new NormalException;
		}
		catch(FieldValueAuthException $e)
		{
			return $e;
		}
		catch(SendEmailException $e)
		{
			return $e;
		}
		catch(NormalException $e)
		{
			return $e;
		}
	}

	/**
	 * 发送反馈信息邮件
	 * @Author   leikes
	 * @datetime 2016-02-16T13:29:25+0800
	 * @param    array                   $data 反馈信息
	 * @return   exception                         发送邮件错误
	 */
	private function sendMail($data)
	{
		try
		{
			$admin=$this->findAllAdmin();
			Mail::queue('emails.feedback.FeedBackEMail', $data, function($message) use($data,$admin)
			{
				foreach($admin as $value){		
					$message->to($value->email)->subject('收到一条反馈信息');
				}   
			});
		}
		catch(Exception $e)
		{
			throw new SendEmailException;
		}
	}

	/**
	 * 查找出所有管理员权限的用户
	 * @Author   Leikes
	 * @DateTime 2016-01-29T16:08:47+0800
	 * @return   Object                   返回所有管理员的对象
	 */
	private function findAllAdmin()
	{
		$admin=Role::find(Config::get('systemConfig.system.role_id.system_admin'))->users()->get();
		return $admin;
	}

	/**
	 * 校验反馈信息
	 * @Author   leikes
	 * @datetime 2016-02-16T14:23:47+0800
	 * @param    [type]                   $data [description]
	 * @return   [type]                         [description]
	 */
	private function verifyFeedBack($data)
	{
		$rules=[
			'comments' =>'required|min:20|max:1000',
			'name'     =>'required',
			'email'    =>'required|email'
		];
		// dd($rules);
		$validation = Validator::make($data,$rules);
		if( $validation->fails() )
		{
			throw new FieldValueAuthException( $validation->messages()->first() );
		}
	}
}
?>